package com.dormitory.dormitorymanagement.service.ipml;



import com.dormitory.dormitorymanagement.mapper.ClassLeaderMapper;
import com.dormitory.dormitorymanagement.mapper.StudentsMapper;
import com.dormitory.dormitorymanagement.pojo.*;
import com.dormitory.dormitorymanagement.pojo.dto.NoticeDto;
import com.dormitory.dormitorymanagement.pojo.dto.UploadTimeTableDto;
import com.dormitory.dormitorymanagement.service.ClassLeaderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
public class ClassLeaderServiceIpml implements ClassLeaderService {

    @Autowired
    ClassLeaderMapper classLeaderMapper;
    @Autowired
    StudentsMapper studentsMapper;
    /**
     * 班级通知
     * @param noticeDto
     */
    public void notice(NoticeDto noticeDto) {
        ClassNotice notice = new ClassNotice();
        Students student = studentsMapper.findByStudentId(noticeDto.getStudentId());
        notice.setTitle(noticeDto.getTitle());
        notice.setContent(noticeDto.getContent());
        notice.setStudentId(noticeDto.getStudentId());
        notice.setStudentName(student.getName());
        notice.setStudentClass(student.getClassName());
        notice.setStudentRole(student.getRole());
        notice.setCreateTime(LocalDateTime.now());
        notice.setUpdateTime(LocalDateTime.now());
        classLeaderMapper.notice(notice);

    }

    /**
     * 上传课表
     * @param uploadTimeTableDto
     * @throws IOException
     */
    public void saveTimetable(UploadTimeTableDto uploadTimeTableDto) throws IOException {
        // 保存文件到服务器
        String fileName = UUID.randomUUID().toString() + "_" + uploadTimeTableDto.getFile().getOriginalFilename();
        String filePath = "uploads/timetables/" + fileName;
//        uploadTimeTableDto.getFile().transferTo(new File(filePath));




        // 保存课表信息到数据库
        CourseUpload  courseUpload = new CourseUpload();
        courseUpload.setSemester(uploadTimeTableDto.getSemester());
        courseUpload.setRemark(uploadTimeTableDto.getRemark());
        courseUpload.setFileName(fileName);
        courseUpload.setFilePath(filePath);
        courseUpload.setStudentId(uploadTimeTableDto.getStudentId());
        Students student = studentsMapper.findByStudentId(uploadTimeTableDto.getStudentId());
        courseUpload.setStudentName(student.getName());
        courseUpload.setUploadTime(LocalDateTime.now());


//        //每次上传先把旧的数据删掉
        List<CourseSchedule> courseSchedule = classLeaderMapper.findByClassName(student.getClassName());
        if(courseSchedule.size() > 0){
            classLeaderMapper.delete(student.getClassName());
        }

        parseExcel(uploadTimeTableDto.getFile(),student.getClassName(),uploadTimeTableDto.getSemester());




        classLeaderMapper.save(courseUpload);


    }


    private List<CourseSchedule> parseExcel(MultipartFile file,String className,String semester) throws IOException {
        List<CourseSchedule> result = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Map<String, Integer> headerMap = getHeaderMap(sheet.getRow(0));

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                CourseSchedule course = new CourseSchedule();
                course.setSemester(semester);
                course.setClassName(className);
                course.setCreateTime(LocalDateTime.now());
                course.setUpdateTime(LocalDateTime.now());
                course.setCourseName(getStringCellValue(row.getCell(headerMap.get("课程名称"))));
                course.setTeacherName(getStringCellValue(row.getCell(headerMap.get("授课教师"))));
                course.setDayOfWeek(getStringCellValue(row.getCell(headerMap.get("星期"))));

                String timePeriod = getStringCellValue(row.getCell(headerMap.get("时间段")));
                course.setTimePeriod(timePeriod);

                // 解析时间段为开始时间和结束时间
//                String[] times = timePeriod.split("-");
//                if (times.length == 2) {
//                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
//                    course.setStartTime(LocalTime.parse(times[0].trim(), formatter));
//                    course.setEndTime(LocalTime.parse(times[1].trim(), formatter));
//                }


                course.setClassroom(getStringCellValue(row.getCell(headerMap.get("上课地点"))));

                classLeaderMapper.add(course);
                result.add(course);
            }
        }

        return result;
    }

    private Map<String, Integer> getHeaderMap(Row headerRow) {
        Map<String, Integer> headerMap = new HashMap<>();
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            headerMap.put(headerRow.getCell(i).getStringCellValue(), i);
        }
        return headerMap;
    }

    private String getStringCellValue(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }


    /**
     * 获取同学的评价
     * @param studentId
     * @param page
     * @param pageSize
     * @return
     */
    public PageBean<StudentEvaluations> getStudentClassmateEvaluations(String studentId, Integer page, Integer pageSize) {
        PageBean<StudentEvaluations> pb = new PageBean<>();

        // 开启分页查询
        PageHelper.startPage(page, pageSize);

        // 执行分页查询
        List<StudentEvaluations> as = classLeaderMapper.getStudentClassmateEvaluations(studentId);


        // 使用PageInfo包装查询结果，获取分页信息
        PageInfo<StudentEvaluations> pageInfo = new PageInfo<>(as);

        // 填充数据到PageBean
        pb.setItems(pageInfo.getList());
        pb.setTotal(pageInfo.getTotal());

        return pb;
    }
}
